<template>
  <div>
    <Card>
      <vxe-grid
        highlight-hover-row
        show-header-overflow
        show-overflow
        ref="xGrid"
        height="600"
        align="center"
        :columns="tableColumn"
        :data="tableData"
        :toolbar-config="tableToolbar"
        :edit-config="{
          trigger: 'manual',
          mode: 'row',
          showStatus: true,
          icon: 'fa fa-file-text-o',
        }"
      >
        <!-- <template #form>
          <Form :model="formData" :label-width="120">
            <FormItem label="查看空间类型：">
              <Row span="10">
                <Col span="180">
                  <Select v-model="formData.typeCode" @on-change="update()">
                    <Option value="区域">区域</Option>
                    <Option value="幢">幢</Option>
                    <Option value="单元">单元</Option>
                    <Option value="房屋">房屋</Option>
                    <Option value="停车区域">停车区域</Option>
                    <Option value="车道空间">车道空间</Option>
                  </Select>
                </Col>
              </Row>
            </FormItem>
          </Form>
        </template> -->

        <template #toolbar_buttons>
          <!-- <Button
            type="primary"
            icon="ios-search"
            style="margin-right: 10px"
            @click="search()"
            >查询
          </Button> -->
          <Button
            type="primary"
            icon="ios-add"
            style="margin-right: 10px"
            @click="openAddForm()"
            >新增
          </Button>
          <Button
            type="primary"
            style="margin-right: 10px"
            icon="md-refresh"
            @click="refreshTable()"
            >刷新
          </Button>
          <Button type="error" style="margin-right: 10px" @click="deleteList()"
            >批量删除
          </Button>
        </template>

        <template #operate="{ row }">
          <Button
            type="primary"
            style="margin-right: 10px"
            @click="editRow(row)"
            >编辑
          </Button>
          <Button
            type="error"
            style="margin-right: 10px"
            @click="deleteRow(row)"
            >删除
          </Button>
          <Button
            type="primary"
            style="margin-right: 10px"
            @click="bind(row)"
            :disabled="row.isBind"

            >绑定
          </Button>
          <Button
            type="error"
            style="margin-right: 10px"
            @click="unbind(row)"
            :disabled="!row.isBind"
            >解绑
          </Button>

        </template>

        <template #pager>
          <div style="text-align: center; padding: 10px">
            <Page
              :current="page.current"
              :total="page.total"
              :page-size="page.pageSize"
              show-elevator
              show-total
              show-sizer
              @on-change="update"
            />
          </div>
        </template>
      </vxe-grid>
      <vxe-modal
        v-model="showEdit"
        :title="selectRow ? '编辑&保存' : '新增&保存'"
        width="800"
        min-width="600"
        min-height="300"
        :loading="submitLoading"
        resize
        destroy-on-close
      >
        <template #default>
          <vxe-form
            ref="addFF"
            :data="addFormData"
            :items="formItems"
            :rules="formRules"
            title-align="right"
            title-width="100"
            @submit="submitForm()"
          >
          </vxe-form>
        </template>
      </vxe-modal>
    </Card>
  </div>
</template>

<script>
import axios from '@/libs/api.request'
export default {
  data () {
    return {
      addFormData: {
        parkId: 1, // 管理员自身属性，园区id
        parentId: null,
        typeCode: null,
        newTypeCode: null,
        parentId_area: null,
        parentId_building: null,
        parentId_unit: null,
        parentId_parkingArea: null,
        direction: null,
        spaceId: null,
        roomSize: null,
        roomCapacity: null,
        isShowHouseInfo: false,
        isShowParkingSpaceChannelInfo: false,
        area: {
          value: [],
          isShow: false
        },
        building: {
          value: [],
          isShow: false
        },
        parkingArea: {
          value: [],
          isShow: false
        },
        parkingSpaceChannel: {
          value: [],
          isShow: false
        },
        unit: {
          value: [],
          isShow: false
        },
        house: {
          value: [],
          isShow: false
        }
      },
      showEdit: false,
      submitLoading: false,
      selectRow: null,

      formData: {
        name: '',
        typeCode: '区域'
      },

      tableToolbar: {
        zoom: true,
        custom: true,
        slots: {
          buttons: 'toolbar_buttons',
          tools: 'toolbar_tools'
        }
      },
      tableColumn: [
        { type: 'checkbox', width: 40, fixed: 'left' },
        // { field: 'spaceId', title: '空间Id', width: 120 },
        { field: 'deviceName', title: '设备名称' },
        { field: 'deviceId', title: '设备Id' },
        { field: 'placeName', title: '已绑定车道空间名称' },
        {
          title: '操作',
          width: 360,
          slots: { default: 'operate' },
          fixed: 'right'
        }
      ],
      page: {
        current: 1,
        total: 100,
        pageSize: 10
      },
      // 展示数据 & 从后端获取来的：
      tableData: [
        {
          deviceName: '第一设备',
          deviceId: 'asdfa',
          placeName: '第一车道',
          isBind: true
        }
      ],
      formRules: {
        // name: [
        //   { required: true, message: '请输入名称' },
        //   { min: 3, max: 5, message: '长度在 3 到 5 个字符' }
        // ],
        // nickname: [
        //   { required: true, message: '请输入昵称' }
        // ],
        // sex: [
        //   { required: true, message: '请选择性别' }
        // ]
      },
      formItems: [
        {
          title: '基本信息',
          span: 24,
          titleAlign: 'left',
          titleWidth: 200,
          titlePrefix: { icon: 'fafa-address-card-o' }
        },
        {
          field: 'newTypeCode',
          title: '空间类型',
          span: 12,
          itemRender: {
            name: '$select',
            events: { change: this.loadSelect },
            options: [
              { label: '区域', value: '区域' },
              { label: '幢', value: '幢' },
              { label: '单元', value: '单元' },
              { label: '房屋', value: '房屋' },
              { label: '停车区域', value: '停车区域' },
              { label: '车道空间', value: '车道空间' }
            ]
          }
        },
        {
          field: 'name',
          title: '空间名称',
          span: 12,
          itemRender: {
            name: '$input',
            props: { placeholder: '请输入空间名称' }
          }
        },
        {
          title: '请按顺序选择父空间',
          span: 24,
          titleAlign: 'left',
          visibleMethod: this.showArea,
          titleWidth: 200,
          titlePrefix: { icon: 'fafa-address-card-o' }
        },
        {
          field: 'parentId_area',
          title: '区域',
          span: 12,
          visibleMethod: this.showArea,
          itemRender: {
            name: '$select',
            options: [
              { label: '1', value: '1' },
              { label: '2', value: '2' }
            ],
            events: { change: this.changeOption }
          }
        },
        {
          field: 'parentId_building',
          title: '幢',
          span: 12,
          visibleMethod: this.showBuilding,
          itemRender: {
            name: '$select',
            options: [
              { label: '1', value: '1' },
              { label: '2', value: '2' }
            ],
            events: { change: this.changeOption }
          }
        },
        {
          field: 'parentId_unit',
          title: '单元',
          span: 12,
          visibleMethod: this.showUnit,
          itemRender: {
            name: '$select',
            options: [
              { label: '1', value: '1' },
              { label: '2', value: '2' }
            ],
            events: { change: this.changeOption }
          }
        },
        {
          field: 'parentId_parkingArea',
          title: '停车区域',
          visibleMethod: this.showParkingArea,
          span: 12,
          itemRender: {
            name: '$select',
            options: [
              { label: '1', value: '1' },
              { label: '2', value: '2' }
            ],
            events: { change: this.changeOption }
          }
        },
        {
          field: 'direction',
          title: '出入口',
          span: 12,
          visibleMethod: this.showParkingSpaceChannelInfo,
          itemRender: {
            name: '$select',
            options: [
              { label: '出口', value: '0' },
              { label: '入口', value: '1' }
            ]
          }
        },
        {
          field: 'roomSize',
          title: '房间大小(㎡)',
          span: 12,
          visibleMethod: this.showHouseInfo,
          itemRender: {
            name: '$input',
            props: { type: 'number', placeholder: '请输入房间大小㎡' }
          }
        },
        {
          field: 'roomCapacity',
          title: '可容纳人数',
          span: 12,
          visibleMethod: this.showHouseInfo,
          itemRender: {
            name: '$input',
            props: { type: 'number', placeholder: '请输入可容纳人数' }
          }
        },
        {
          align: 'center',
          span: 24,
          titleAlign: 'left',
          itemRender: {
            name: '$buttons',
            children: [
              { props: { type: 'submit', content: '提交', status: 'primary' } },
              { props: { type: 'reset', content: '重置' } }
            ]
          }
        }
      ]
    }
  },
  mounted () {
    this.update()
  },

  methods: {
    update () {

    },
    toLine (name) {
      return name.replace(/([A-Z])/g, '_$1').toLowerCase()
    },
    submitForm () {
      this.submitLoading = true
      if (this.selectRow) {
        axios
          .request({
            method: 'post',
            url: 'space/update',
            data: {
              name: this.addFormData.name,
              spaceId: this.addFormData.spaceId,
              direction: this.addFormData.direction,
              roomSize: parseInt(this.addFormData.roomSize),
              roomCapacity: parseInt(this.addFormData.roomCapacity)
            }
          })
          .then((res) => {
            console.log('update', res)
            this.submitLoading = false
            this.showEdit = false
            this.selectRow = false
            this.update()
            this.$XModal.message({ content: '保存成功', status: 'success' })
          })
          .catch((err) => {
            console.log(111)
            console.log(err)
          })
      } else { // add
        axios
          .request({
            method: 'post',
            url: 'space/add',
            data: {
              name: this.addFormData.name,
              parentId: this.addFormData.parentId,
              typeCode: this.addFormData.newTypeCode,
              direction: this.addFormData.direction,
              roomSize: this.addFormData.roomSize,
              roomCapacity: this.addFormData.roomCapacity
            }
          })
          .then((res) => {
            console.log('add', res)
            this.submitLoading = false
            this.showEdit = false
            this.update()
            this.$XModal.message({ content: '保存成功', status: 'success' })
          })
          .catch((err) => {
            console.log(err)
          })
      }
    },
    subSpaceQuery (
      typeCode = '区域',
      spaceId = null,
      pageSize = 1000,
      current = 1
    ) {
      return new Promise((resolve, reject) => {
        // 通过传入参数进行查询：
        axios
          .request({
            method: 'post',
            url: 'space/sub/query',
            data: {
              typeCode: typeCode,
              pageSize: pageSize,
              pageNum: current,
              spaceId: spaceId
            }
          })
          .then((res) => {
            console.log('query', res)
            const records = res.data.msg.records
            resolve(records)
          })
          .catch((err) => {
            console.log(err)
            reject(err)
          })
      })
    },
    spaceQuery () {
      return new Promise((resolve, reject) => {
        axios
          .request({
            method: 'post',
            url: 'space/sub/query',
            data: {
              typeCode: this.formData.typeCode,
              pageSize: this.page.pageSize,
              pageNum: this.page.current
            }
          })
          .then((res) => {
            const resDatas = res.data.msg
            this.tableData = resDatas.records
            resolve()
          })
          .catch((err) => {
            console.log(err)
            reject(err)
          })
      })
    },
    get_park_info () {
      axios
        .request({
          method: 'get',
          url: 'park/info/access', //
          data: {
            parkId: 1
          }
        })
        .then((res) => {
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    search () {
      this.spaceQuery()
    },
    openAddForm () {
      this.showEdit = true
      this.selectRow = false
      this.addFormData = {
        parkId: 1, // 管理员自身属性，园区id
        parentId: 1,
        newTypeCode: null,
        parentId_area: null,
        parentId_building: null,
        parentId_unit: null,
        parentId_parkingArea: null,
        direction: null,
        roomSize: null,
        roomCapacity: null,
        area: {
          value: [],
          isShow: false
        },
        building: {
          value: [],
          isShow: false
        },
        parkingArea: {
          value: [],
          isShow: false
        },
        parkingSpaceChannel: {
          value: [],
          isShow: false
        },
        unit: {
          value: [],
          isShow: false
        },
        house: {
          value: [],
          isShow: false
        }
      }
    },

    showArea () {
      return this.addFormData.area.isShow
    },
    showBuilding () {
      return this.addFormData.building.isShow
    },
    showUnit () {
      return this.addFormData.unit.isShow
    },
    showHouseInfo () {
      return this.addFormData.isShowHouseInfo
    },
    showParkingArea () {
      return this.addFormData.parkingArea.isShow
    },
    showParkingSpaceChannelInfo () {
      return this.addFormData.isShowParkingSpaceChannelInfo
    },

    updateValue (place, records) {
      const l = records.length
      // if (l > 0) {
      place.value = []
      for (var i = 0; i < l; i++) {
        place.value.push({
          label: records[i].name,
          value: records[i].spaceId
        })
      }
      // }
      // else {
      //   place.value.push({
      //     label: '无项目',
      //     value: 1
      //   })
      // }
    },
    loadSelect (value) {
      this.addFormData.area.isShow = false
      this.addFormData.building.isShow = false
      this.addFormData.parkingArea.isShow = false
      this.addFormData.parkingSpaceChannel.isShow = false
      this.addFormData.unit.isShow = false
      if (this.addFormData.newTypeCode === '区域') {
      } else {
        this.subSpaceQuery().then((records) => {
          this.updateValue(this.addFormData.area, records)
          this.formItems[4].itemRender.options = this.addFormData.area.value
          this.addFormData.area.isShow = true
        })
        this.addFormData.area.isShow = true
        if (this.addFormData.newTypeCode === '单元') {
          this.addFormData.building.isShow = true
        }
        if (this.addFormData.newTypeCode === '房屋') {
          this.addFormData.building.isShow = true
          this.addFormData.unit.isShow = true
          this.addFormData.isShowHouseInfo = true
        }
        if (this.addFormData.newTypeCode === '车道空间') {
          this.addFormData.parkingArea.isShow = true
          this.addFormData.isShowParkingSpaceChannelInfo = true
        }
      }
    },
    changeOption (value, $event) {
      this.$Message.success('ChangeOption')
      // refreshOption()
      console.log(value)
      // for select area:
      if (value.property === 'parentId_area') {
        this.addFormData.parentId = value.data.parentId_area

        if (this.addFormData.building.isShow) {
          this.subSpaceQuery('幢', this.addFormData.parentId).then(
            (records) => {
              console.log(records, 'records')
              this.updateValue(this.addFormData.building, records)
              this.formItems[5].itemRender.options =
                this.addFormData.building.value
            }
          )
        }

        if (this.addFormData.parkingArea.isShow) {
          this.subSpaceQuery('停车区域', this.addFormData.parentId).then(
            (records) => {
              this.updateValue(this.addFormData.parkingArea, records)
              this.formItems[7].itemRender.options =
                this.addFormData.parkingArea.value
            }
          )
        }
      }
      // for select  building:
      if (value.property === 'parentId_building') {
        this.addFormData.parentId = value.data.parentId_building
        // value.data.parentId_building = null
        if (this.addFormData.building.isShow) {
          this.subSpaceQuery('单元', this.addFormData.parentId).then(
            (records) => {
              this.updateValue(this.addFormData.unit, records)
              this.formItems[6].itemRender.options =
                this.addFormData.unit.value
            }
          )
        }
      }
    },

    deleteList (row) {
      // 获取选中的数据
      const selectedRecords = this.$refs.xGrid.getCheckboxRecords()
      console.log(selectedRecords)
    },
    editRow (row) {
      // console.log(row, 'hello')
      this.showEdit = true
      this.addFormData.isShowHouseInfo = false
      this.addFormData.isShowParkingSpaceChannelInfo = false
      this.selectRow = true
      console.log(row)
      this.addFormData.name = row.name
      this.addFormData.spaceId = row.spaceId
      this.addFormData.parentId = row.parentId
      this.addFormData.direction = row.direction
      this.addFormData.roomSize = row.roomSize
      this.addFormData.roomCapacity = row.roomCapacity
      this.addFormData.newTypeCode = row.typeCode
      if (row.typeCode === '房屋') {
        this.addFormData.isShowHouseInfo = true
      }
      if (row.typeCode === '车道空间') {
        this.addFormData.isShowParkingSpaceChannelInfo = true
      }
    },
    deleteRow (row) {
      // console.log(row)

      this.$Modal.confirm({
        title: '操作确认',
        content: '您确定要删除"' + row.name + '"吗',
        onOk: () => {
          const spaceId = row.spaceId
          console.log(spaceId)
          axios
            .request({
              method: 'get',
              url: 'space/delete',
              params: {
                spaceId: spaceId
              }
              // data:{ post, 放到请求头里面
              // }
            })
            .then((res) => {
              console.log(res)
              this.update()
              this.$Message.success('删除成功')
            })
            .catch((err) => {
              console.log(err)
            })
          // this.tableData.splice(idx, 1) // 返回被删除的数组
        },
        onCancel: () => {}
      })
    },
    refreshTable () {}
  }
}
</script>
